package com.sharp.socket.io.dao.msyql.repository;

import com.sharp.kernel.constant.db.SqlConstant;
import com.sharp.kernel.mybatis.repository.BaseMysqlRepository;
import com.sharp.socket.io.constant.dict.RoomRoleDict;
import com.sharp.socket.io.dao.msyql.entity.ChatRoomMember;
import com.sharp.socket.io.dao.msyql.mapper.ChatRoomMemberDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * Title: ChatRoomMemberService
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2022/6/17 14:35
 */
@Service
public class ChatRoomMemberService extends BaseMysqlRepository<ChatRoomMember, ChatRoomMemberDao> {

    @Resource
    private ChatRoomMemberDao chatRoomMemberDao;

    @Cacheable
    public List<ChatRoomMember> getMemberListByRoomId(String roomId) {
        Example example = super.getExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roomId", roomId);
        criteria.andEqualTo(SqlConstant.VALID_FIELD, SqlConstant.VALID);
        return super.select(example);
    }

    public List<ChatRoomMember> getRoomListByUserId(String userId) {
        Example example = super.getExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        criteria.andEqualTo("valid", SqlConstant.VALID);
        return super.select(example);
    }

    public List<ChatRoomMember> getRoomListByUserIdAndRoomId(String userId, String roomId) {
        Example example = super.getExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        if (StringUtils.isNotBlank(roomId)) {
            criteria.andEqualTo("roomId", roomId);
        }
        criteria.andEqualTo(SqlConstant.VALID_FIELD, SqlConstant.VALID);
        return super.select(example);
    }

    public void deleteByRoomId(String roomId) {
        Example example = super.getExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roomId", roomId);
        criteria.andEqualTo(SqlConstant.VALID_FIELD, SqlConstant.VALID);
        super.delete(example);
    }

    public void deleteByRoomIdAndUserId(String roomId, String userId) {
        Example example = super.getExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roomId", roomId);
        criteria.andEqualTo("userId", userId);
        criteria.andNotEqualTo("role", RoomRoleDict.OWNER.getValue());
        criteria.andEqualTo(SqlConstant.VALID_FIELD, SqlConstant.VALID);
        super.delete(example);
    }

}
